const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const path = require('path')
const {koaBody} = require('koa-body');
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const mongoose = require('mongoose');


mongoose.connect('mongodb://node:123456@114.132.75.251:27017/nodeTest').then(r=>{
  console.log('数据库链接成功')
});

// db.createUser(
//     {
//       user: "node",
//       pwd: "123456",
//       roles: [ { role: "dbOwner", db: "nodeTest" } ]
//     }
// )

const index = require('./routes/index')


// error handler
onerror(app)

// middlewares
app.use(koaBody({
  multipart: true,
  formidable: {
    uploadDir: path.join(__dirname, '/public/uploads'),
    keepExtensions: true,
  },
}));

app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))



app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(index.routes(), index.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
